<template>
  <x-table ref="table" :isPage="true" @search="onSearch" @assign="onAssignUser" @cancel="onCancel" showCheckbox>
    <template v-slot:btn-tool>
      <el-button type="primary" @click="onAssignUsers">批量分配</el-button>
    </template>
    <template #status="scope">
      <el-tag :type="scope.data.status == 0 ? '' : 'info'">{{ scope.data.status == 0 ? "正常" : "停用" }}</el-tag>
    </template>
  </x-table>
</template>

<script setup name="user-list">
import useStore from '@/stores/modules/sys/hook/assignUser';
const assignUser = useStore()
import {onMounted, ref} from "vue";

onMounted(() => {
  assignUser.init(table)
  assignUser.getList(1, 10);
})

let table = ref();
let roleInfo = {}

/**
 * 搜索
 * @param pageNo
 * @param pageSize
 * @param condition
 */
const onSearch = (pageNo, pageSize, condition) => {
  assignUser.getList(pageNo, pageSize, condition);
}

/**
 * 来自角色列表数据
 * @param data
 */
const render = (data) => {
  roleInfo = data
  assignUser.userList = roleInfo.userList
}

/**
 * 分配
 * @param row
 */
const onAssignUser = (row) => {
  let userList = Object.assign([], assignUser.userList)
  userList.push(row.id)
  assignUser.userSave(roleInfo.id, userList)
}

/**
 * 批量分配
 */
const onAssignUsers = () => {
  let rows = table.value.getSelectRows()
  if (Helper.emptyArray(rows)) {
    Msg.error("请至少选择一个用户")
    return
  }

  let idList = []
  rows.forEach(row => { idList.push(row.id) })

  let userList = idList.concat(assignUser.userList)
  userList = arrayReduction(userList)

  assignUser.userSave(roleInfo.id, userList)
}

/**
 * 取消分配
 * @param row
 */
const onCancel = (row) => {
  Msg.confirm("是否取消分配？").then(_ => {
    let userList = Object.assign([], assignUser.userList)
    let index = userList.findIndex(id => id == row.id)
    userList.splice(index, 1)

    assignUser.userSave(roleInfo.id, userList)
  })
}

/**
 * 数组去重
 * @param userList
 * @returns {*[]}
 */
const arrayReduction = (userList) => {
  let newArray = []
  for (let i = 0; i < userList.length; i++) {
    if (newArray.indexOf(userList[i]) == -1) {
      newArray.push(userList[i])
    }
  }
  return newArray
}
defineExpose({ render })
</script>